package net.obxlabs.tweetpad.behaviour;

import net.nexttext.*;
import net.nexttext.behaviour.*;
import net.nexttext.property.*;

public class Reorder extends AbstractAction {
	/**
	 * Builds a default Reorder.
	 */
	public Reorder() {
		this(5);
	}
	
	/**
	 * Builds a Reorder.
	 * 
	 * @param speed the TextObjects should move at
	 */
	public Reorder(long speed) {
		properties().init("Speed", new NumberProperty(speed));
	}
	
	/**
     * Adds a vector to the position to bring the TextObject closer to its origin.
     * <p>Result is complete when the TextObject returns to its origin. </p>
     */
    public ActionResult behave(TextObject to) {
    	ActionResult result = new ActionResult(true, true, false);

    	double speed = ((NumberProperty)properties().get("Speed")).get();
        
    	Vector3 targetPos;
    	Vector3Property targetProp = (Vector3Property)to.getProperty("TargetReorderPosition");
    	if (targetProp == null) {
    		to.getBook().log("Reorder: TargetReorderPosition property not found! Using original position.");
    		targetPos = to.getPosition().getOriginal();
    	} else {
    		targetPos = targetProp.get();
    	}
		//Vector3 targetPos = targetProp.get();
    	//Vector3 targetPos = to.getPosition().getOriginal();
	    Vector3 currPos = to.getPosition().get();
	    targetPos.sub(currPos);

		// scale the vector down to the speed if needed
	    if (targetPos.length() > speed) {
	        try {
	        	targetPos.normalize();
	        } catch (Vector3ArithmeticException v3ae) {
	            // some silly person set a negative speed, and the object had
	            // already arrived at it's location, just ignore the problem.
	        }
	        targetPos.scalar(speed);
	        result.complete = false;
	    }
	        
	    to.getPosition().add(targetPos);
	    
	    return result;
    }
}
